package com.junxonline.instant.terminal.listener;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.reflect.TypeToken;
import com.junxonline.instant.common.constant.DataSourceConstant;
import com.junxonline.instant.common.constant.RedisMqChannelConstant;
import com.junxonline.instant.common.constant.SQLConstant;
import com.junxonline.instant.dao.entity.model.logDevice.LogDeviceConnect;
import com.junxonline.instant.dao.entity.model.device.Terminal;
import com.junxonline.instant.dao.mapper.logDevice.LogDeviceConnectMapper;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 终端连接日志消费者
 *
 * @author JunX
 * @date 2022-05-19
 */
@Log4j2
@Component
public class TerminalConnectListener implements MessageListener {

    @Autowired
    private LogDeviceConnectMapper logDeviceConnectMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    /**
     * 消息处理
     *
     * @param message 消息
     */
    @Override
    @DS(DataSourceConstant.SHARDING)
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        String msg = (String) serializer.deserialize(message.getBody());
        log.info("收到频道[" + RedisMqChannelConstant.KEY_REDIS_MSG_CHANNEL_LOG_DEVICE_CONNECT + "]消息 => {}", msg);
        HashMap<String, Object> data = JSON.parseObject(msg, new TypeToken<HashMap<String, Object>>(){}.getType());
        if (data != null) {
            String terminalCode = (String) data.get("terminalCode");
            Integer type = (Integer) data.get("type");
            Terminal terminal = terminalMapper.selectOne(new LambdaQueryWrapper<Terminal>().eq(Terminal::getCode, terminalCode).last(SQLConstant.LIMIT_1));
            if (terminal != null) {
                // 插入日志
                LogDeviceConnect logDeviceConnect = new LogDeviceConnect();
                logDeviceConnect.setTerminalCode(terminalCode);
                logDeviceConnect.setType(type);
                logDeviceConnect.setOrganizationId(terminal.getOrganizationId());
                logDeviceConnect.setCreateTime(DateUtil.date());
                logDeviceConnectMapper.insert(logDeviceConnect);
            }
        }

    }

}
